package com.zhang.user.service.impl;

import com.zhang.dubbo.api.code.CodeRpcApi;
import com.zhang.dubbo.api.user.UserRpcApi;
import com.zhang.user.dao.SysTokenDao;
import com.zhang.user.dao.SysUserInfoDao;
import com.zhang.user.pojo.po.SysTokenPo;
import com.zhang.user.pojo.po.SysUserInfoPo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.UUID;

@Service(timeout = 20000)
@Component
public class UserServiceImpl implements UserRpcApi {
    @Autowired
    private SysTokenDao sysTokenDao;

    @Autowired
    private SysUserInfoDao sysUserInfoDao;

    @Reference
    private CodeRpcApi codeRpcApi;


    @Override
    public String register(String email, String password, String code) {
        SysUserInfoPo userPo = sysUserInfoDao.findByEmail(email);
        if (Objects.nonNull(userPo)) {
            return "false";
        }
        String check = codeRpcApi.checkCode(email, code);
        if (check.equals("true")) {
            SysTokenPo tokenPo = new SysTokenPo();
            String token = UUID.randomUUID().toString();
            tokenPo.setEmail(email);
            tokenPo.setToken(token);
            sysTokenDao.save(tokenPo);
            SysUserInfoPo userInfoPo = new SysUserInfoPo();
            userInfoPo.setEmail(email);
            userInfoPo.setPassword(password);
            sysUserInfoDao.save(userInfoPo);
            return token;
        } else {
            return "false";
        }
    }

    @Override
    public String registered(String email) {
        SysUserInfoPo userInfoPo = sysUserInfoDao.findByEmail(email);
        return Objects.isNull(userInfoPo) ? "false" : "true";
    }

    @Override
    public String login(String email, String password) {
        SysUserInfoPo sysUserInfoPo = sysUserInfoDao.findByEmailAndPassword(email, password);
        if (Objects.nonNull(sysUserInfoPo)) {
            SysTokenPo tokenPo = new SysTokenPo();
            String token = UUID.randomUUID().toString();
            tokenPo.setEmail(email);
            tokenPo.setToken(token);
            sysTokenDao.save(tokenPo);
            return token;
        } else {
            return "false";
        }
    }

    @Override
    public String getInfo(String token) {
        SysTokenPo tokenPo = sysTokenDao.findByToken(token);
        return tokenPo.getEmail();
    }
}
